package com.sbwebsocket.example.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sbwebsocket.core.model.bo.*;
import com.sbwebsocket.core.redis.model.contants.WsMessageRedisKeyPrefix;
import com.sbwebsocket.core.service.MessageQueueAdapter;
import com.sbwebsocket.core.service.TopicMessageManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Auther: GSJ
 * @Date: 2022/2/16
 * @Description:
 * @version: 1.0
 */
@RestController
public class ManagerController {

    @Autowired
    private MessageQueueAdapter messageQueueAdapter;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;
    
    @Autowired
    private TopicMessageManager topicMessageManager;

    @PostMapping("/message/direct/send")
    public boolean send(@RequestBody DirectMessageBody body){
        return messageQueueAdapter.get(body).delivery(body);
    }

    @PostMapping("/message/fanout/send")
    public boolean send(@RequestBody FanoutMessageBody body){
        return messageQueueAdapter.get(body).delivery(body);
    }

    @PostMapping("/message/topic/send")
    public boolean send(@RequestBody TopicMessageBody body){
        return messageQueueAdapter.get(body).delivery(body);
    }

    /**
     * 订阅主题
     * @param subscribe
     * @return
     */
    @PostMapping("/message/topic/_subscribe")
    public boolean topicSubscribe(@RequestBody TopicSubscribe subscribe){
        return topicMessageManager.subscribe(subscribe.getClientIdentitys(),subscribe.getTopic());
    }

    /**
     * 取消订阅主题
     * @param subscribe
     * @return
     */
    @PostMapping("/message/topic/_unsubscribe")
    public boolean topicUnsubscribe(@RequestBody TopicSubscribe subscribe){
        return topicMessageManager.unsubscribe(subscribe.getClientIdentitys().get(0),subscribe.getTopic());
    }

    @PostMapping("/send/cycleUnusualOffline")
    public boolean append(@RequestParam Integer delayTime,@RequestBody UnusualMessage msg) throws JsonProcessingException {
        long l = delayTime*1000 + System.currentTimeMillis();
        String jsonkey = objectMapper.writeValueAsString(msg);
        return stringRedisTemplate.opsForZSet().add(WsMessageRedisKeyPrefix.UNUSUAL_MSG_LIST,jsonkey,l);
    }
}
